package com.zky.user.service.impl;

import com.zky.basic.exception.BusinessException;
import com.zky.org.domain.Employee;
import com.zky.user.domain.Logininfo;
import com.zky.user.domain.User;
import com.zky.user.mapper.LogininfoMapper;
import com.zky.user.mapper.UserMapper;
import com.zky.user.service.IUserService;
import com.zky.basic.service.impl.BaseServiceImpl;
import com.zky.util.Md5Utils;
import com.zky.util.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void phoneRegister(Map<String, String> map) {

        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String password = map.get("password");
        String repassword = map.get("repassword");

        //判断空值
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(phoneCode)
                ||StringUtils.isEmpty(password)||StringUtils.isEmpty(repassword)){
            throw new BusinessException("信息不能为空");
        }
        //判断两次密码是否相等
        if (!password.equals(repassword)){
            throw new BusinessException("请确认密码");
        }
        //校验验证码是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        //校验验证码是否过期
        if(obj == null){
            throw new BusinessException("验证码已经过期");
        }
        if (!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("验证码错误");
        }

        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

    }

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {

        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");


        //判断空值
        if (StringUtils.isEmpty(email)
                ||StringUtils.isEmpty(password)||StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空");
        }
        //判断是否注册过
        User user = userMapper.findByEmail(email);
        if (user!=null){
            throw new BusinessException("当前邮箱号已注册，请登录，如果忘记密码，请联系管理员");
        }

        //判断两次密码是否相等
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("请确认密码");
        }

        if (redisTemplate.opsForValue().get(email)!=null){
            throw new BusinessException("当前邮箱号已注册，请激活");
        }

        redisTemplate.opsForValue().set(email,password,5,TimeUnit.MINUTES);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setFrom("2315279694@qq.com");
        helper.setSubject("账号激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h3>你的账号已经注册成功，请<a href='http://127.0.0.1:8080/user/active/"+email+"'>点击这里</a>激活邮件</h3>", true);
        //店铺管理员
        helper.setTo(email);
        //发送
        javaMailSender.send(mimeMessage);



    }

    @Override
    public void emailActive(String emailKey) {
        Object password = redisTemplate.opsForValue().get(emailKey);
        if(password==null){
            throw new BusinessException("激活失败，请重新注册");
        }


        Logininfo logininfo = new Logininfo();
        logininfo.setEmail(emailKey);
        logininfo.setUsername(emailKey);
        logininfo.setType(1);
        logininfo.setDisable(true);
        String salt = StrUtils.getComplexRandomString(32);
        String md5Password = Md5Utils.encrypByMd5(password.toString() + salt);
        logininfo.setPassword(md5Password);
        logininfo.setSalt(salt);

        logininfoMapper.add(logininfo);

        User user = logininfo2User(logininfo);
        user.setLogininfoId(logininfo.getId());
        user.setState(1);
        userMapper.add(user);

    }

    private User logininfo2User(Logininfo logininfo) {
        User user = new User();
        BeanUtils.copyProperties(logininfo,user);
        return user;
    }

    /**
     * 传值方法，将user的值赋值给logininfo
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //工具类，根据同名属性进行传值
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    /**
     * 传值方法，将map的值赋值给user
     * @param
     * @return
     */
    private User map2User(Map<String, String> map) {
        User user = new User();
        user.setUsername(map.get("phone"));
        user.setPhone(map.get("phone"));
        String salt = StrUtils.getComplexRandomString(32);
        String md5Password = Md5Utils.encrypByMd5(map.get("password") + salt);
        user.setPassword(md5Password);
        user.setSalt(salt);
        user.setState(1);
        return user;
    }
    @Override
    @Transactional
    public void add(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }
    @Override
    @Transactional
    public void delete(Long id) {
        //先查询登陆信息id
        User user = userMapper.findOne(id);

        //删除user
        super.delete(id);

        //删除logininfo
        logininfoMapper.delete(user.getLogininfoId());
    }
    @Override
    @Transactional
    public void update(User user) {//前端传过来的user是没有登陆信息id
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.findOne(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.findOne(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

}
